package com.blog.blog.service.impl;

import com.blog.blog.service.ResumePdfService;
import com.blog.blog.service.ResumeService;
import com.blog.blog.vo.ResumeDetailVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 简历PDF导出服务实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ResumePdfServiceImpl implements ResumePdfService {
    
    private final ResumeService resumeService;
    private final TemplateEngine templateEngine;
    
    @Override
    public byte[] generateResumePdf(Long userId) {
        try {
            // 获取简历数据
            ResumeDetailVO resume = resumeService.getResumeByUserId(userId);
            if (resume == null) {
                log.warn("用户{}的简历数据不存在", userId);
                return null;
            }
            
            return generateResumePdf(resume);
            
        } catch (Exception e) {
            log.error("生成简历PDF失败，用户ID: {}", userId, e);
            return null;
        }
    }
    
    @Override
    public byte[] generateResumePdf(ResumeDetailVO resume) {
        try {
            // 生成HTML内容
            String htmlContent = generateHtmlContent(resume);
            
            // 转换为PDF
            return convertHtmlToPdf(htmlContent);
            
        } catch (Exception e) {
            log.error("生成简历PDF失败", e);
            return null;
        }
    }
    
    @Override
    public boolean generateResumePdfToFile(Long userId, String filePath) {
        try {
            byte[] pdfBytes = generateResumePdf(userId);
            if (pdfBytes == null) {
                return false;
            }
            
            try (FileOutputStream fos = new FileOutputStream(filePath)) {
                fos.write(pdfBytes);
                return true;
            }
            
        } catch (Exception e) {
            log.error("生成简历PDF文件失败，用户ID: {}, 文件路径: {}", userId, filePath, e);
            return false;
        }
    }
    
    @Override
    public String getResumePdfFileName(Long userId) {
        try {
            ResumeDetailVO resume = resumeService.getResumeByUserId(userId);
            if (resume == null || resume.getName() == null) {
                return "resume_" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")) + ".pdf";
            }
            
            String name = resume.getName();
            if (name.trim().isEmpty()) {
                name = "resume";
            } else {
                // 清理文件名中的特殊字符
                name = name.replaceAll("[^\\w\\u4e00-\\u9fa5]", "_");
            }
            
            String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            return name + "_简历_" + timestamp + ".pdf";
            
        } catch (Exception e) {
            log.error("生成简历PDF文件名失败，用户ID: {}", userId, e);
            return "resume_" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")) + ".pdf";
        }
    }
    
    private String generateHtmlContent(ResumeDetailVO resume) {
        Context context = new Context();
        context.setVariable("resume", resume);
        context.setVariable("generateTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy年MM月dd日")));
        
        return templateEngine.process("pdf/resume", context);
    }
    
    private byte[] convertHtmlToPdf(String htmlContent) throws Exception {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        
        try {
            ITextRenderer renderer = new ITextRenderer();
            
            // 设置HTML内容
            renderer.setDocumentFromString(htmlContent);
            renderer.layout();
            
            // 生成PDF
            renderer.createPDF(outputStream);
            
            return outputStream.toByteArray();
            
        } finally {
            outputStream.close();
        }
    }
}